package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// 通过这个类完成对 user 表的操作
public class UserDao {
    // 1. 根据 userId 查询对应用户的信息
    public User getByUserId(int userId) {

        // 先将需要用到的资源定义出来
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 1. 通过 DBUtil 获取连接
            connection = DBUtil.getConnection();
            // 2. 编写SQL
            String sql = "select * from user where user_id=?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, userId);
            // 3. 执行SQL 得到结果集
            resultSet = statement.executeQuery();
             if (resultSet.next()) {
                 // 4. 遍历结果集 构造 user 对象
                 User user = new User();
                user.setUserId(resultSet.getInt("user_id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 5. 关闭资源
            DBUtil.close(connection, statement, resultSet);
        }
        return null;
    }

    // 2. 根据 username 查询对应用户的信息 (用来登录)
    public User getByUsername(String username) {
        // 先将需要用到的资源定义出来
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 1. 通过 DBUtil 获取连接
            connection = DBUtil.getConnection();
            // 2. 编写SQL
            String sql = "select * from user where username=?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            // 3. 执行SQL 获取结果集
            resultSet = statement.executeQuery();
            if(resultSet.next()) {
                // 4. 遍历结果集 构造 user 对象
                User user= new User();
                user.setUserId(resultSet.getInt("user_id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 5. 关闭资源
            DBUtil.close(connection, statement, resultSet);
        }
        return null;
    }
}
